#! /bin/bash

die(){ echo >&2 "!! $*"; exit 1; }

test -z "$RESALLOC_NAME" && die "no vm specified, empty \$RESALLOC_NAME variable"

# Try to, best effort, remove the entitlement.
set -- $(echo "$RESALLOC_RESOURCE_DATA" | base64 --decode)

# Don't give-up unregistering after the first attempt
for _ in a b c; do
    ssh root@"$1" "subscription-manager unregister" && break
    sleep 5
done

case "$RESALLOC_POOL_ID" in
*aws*)
    # Delegate the rest of the task to an AWS specific script.
    exec /usr/bin/resalloc-aws-delete --aws-profile default
    exit 1
    ;;
copr_osuosl_p09_*)
    # Delegate the rest of this task to an OpenStack specific script.
    . "{{ provision_directory }}/.rc-osuosl.sh"
    resalloc-openstack-delete --delete-everything "$RESALLOC_NAME"
    exit 1
    ;;
*s390x*)
    # Delegate the rest of the task to the IBM Cloud specific script.
    exec /var/lib/resallocserver/resalloc_provision/ibm-cloud-vm --log-level debug delete "$RESALLOC_NAME"
    exit 1
    ;;
*copr_hv_x86_64_*)
    pool_id=${RESALLOC_POOL_ID//copr_hv_x86_64_/}
    pool_id=${pool_id//_dev/}
    pool_id=${pool_id//_prod/}
    pool_id=${pool_id//_stg/}
    conn=qemu+ssh://copr@vmhost-x86-copr${pool_id}.rdu-cc.fedoraproject.org/system
    ;;

*aarch64_01*)
    conn=qemu+ssh://copr@virthost-aarch64-os01.fedorainfracloud.org/system
    ;;

*aarch64_02*)
    conn=qemu+ssh://copr@virthost-aarch64-os02.fedorainfracloud.org/system
    ;;

*copr_hv_ppc64le_*):
    pool_id=${RESALLOC_POOL_ID//copr_hv_ppc64le_/}
    pool_id=${pool_id//_dev/}
    pool_id=${pool_id//_prod/}
    pool_id=${pool_id//_stg/}
    conn=qemu+ssh://copr@vmhost-p08-copr${pool_id}.rdu-cc.fedoraproject.org/system
    ;;

copr_p09_01*)
    pool_id=${RESALLOC_POOL_ID//copr_p09_/}
    pool_id=${pool_id//_dev/}
    pool_id=${pool_id//_prod/}
    pool_id=${pool_id//_stg/}
    conn=qemu+ssh://copr@vmhost-p09-copr${pool_id}.rdu-cc.fedoraproject.org/system
    ;;

*) die "unknown RESALLOC_POOL_ID=$RESALLOC_POOL_ID" ;;
esac

# The rest of this script is LibVirt only!
{{ provision_directory }}/libvirt-delete --connection "$conn" "$RESALLOC_NAME"
